package com.platform.mobile.operator;

import java.util.LinkedHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.platform.base.SysException;
import com.platform.mobile.bean.LoginAssitantInfo;
import com.platform.mobile.bean.LoginRequest;
import com.platform.mobile.bean.LoginResponse;
import com.platform.mobile.bean.ReqBean;
import com.platform.mobile.bean.ResBean;
import com.platform.mobile.bean.ResultBean;
import com.platform.mobile.factory.Operator;
import com.platform.mobile.service.MLoginService;
import com.platform.mobile.session.SessionManager;
import com.platform.mobile.session.SessionUtil;
import com.platform.mobile.session.UserSession;

@Component
public class Login extends Operator{

	private static Logger log = LoggerFactory.getLogger(Login.class);
	
	@Autowired
	private MLoginService service;
	
	@Override
	public ResBean operate(ReqBean reqBean) throws SysException {
		
		log.info("进入到Login业务处理类，处理[" + reqBean.getClientInfo() + "]用户请求");
		ResBean resBean = new ResBean();
		LoginRequest request = new LoginRequest();
		
		String sid = SessionUtil.generateSessionId();
		ResultBean result = new ResultBean();
		
		LoginResponse response = new LoginResponse();
		try{
			Object params = reqBean.getParams();
			if(params != null){
				/*request 
					= JsonUtils.readValue(params.toString(),LoginRequest.class);*/
				
				@SuppressWarnings("unchecked")
				LinkedHashMap<String, Object> paramMap = (LinkedHashMap<String, Object>)params;
			    request.setUsername(paramMap.get("username").toString());
			    request.setPassword(paramMap.get("password").toString());
				
				LoginAssitantInfo assitant 
					= service.checkUserInfo(request);
				
				/**
				 * 添加session信息
				 */
				UserSession session = new UserSession();
				session.setObj(assitant);
				SessionManager.getInstance().addSessionInfo(sid, session);
				
				/** 临时代码，暂时测试用*/
				if(assitant != null){
					response.setSid(sid);
					response.setAssitant(assitant);
					response.setDoctor_array(
							service.getDoctorArray(response.getAssitant().getId()));
					
					resBean.setMethod("login");
					resBean.setJsonrpc("2.0");
					
					result.setResultStatus("1");
					result.setInfo("登陆成功");
					result.setData(response);
					
				} else {
					result.setResultStatus("0");
					result.setInfo("登陆失败，助理不存在");
					result.setData(null);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			result.setResultStatus("0");
			result.setInfo("服务器异常");
			result.setData(null);
		}
		
		
		resBean.setResult(result);
		return resBean;
	}

}
